import config from '@/config/app'
import store from "@/store"
// import appStore from '@/stores/app'
const install = (Vue, vm) => {
  Vue.prototype.$u.http.setConfig({
    baseUrl: config.baseUrl,
    dataType: 'json',
    showLoading: true,
    loadingText: '请求中...',
    loadingTime: 800,
    originalData: false,
    loadingMask: true,
    headers: config.HEADER,
    isAuth: false,
    withToken: true,
  });
  Vue.prototype.$u.http.interceptor.request = (config, options) => {
    // console.log('request:', config, options);
    // console.log('store.state.token', store.state.token);
    config.data = config.data || {}
    if (!config.header.token) {
      config.header.token = store.state.token || null
    }
    return config;
  }
  // 响应拦截，判断状态码是否通过
  Vue.prototype.$u.http.interceptor.response = (res, options) => {
    const { isAuth } = options
    // console.log('options', options);
    const {
      code,
      data,
      msg,
      show
    } = res;
    switch (code) {
      case 1:
        msg && show && uni.$u.toast(msg)
        return data;
      case 0:
        uni.$u.toast(msg)
        return Promise.reject(msg)

      case -1: {
        store.commit('LOGOUT');
        if (isAuth && !store.state.token) {
            uni.navigateTo({
                url: '/pages/login/login'
            })
        }
    
        return Promise.reject(msg)
      }

      default:
        return data
    }

  }, (options, err) => {
    uni.$u.toast('网络异常')
    delete this.queue[options.url];
    if (Object.keys(this.queue).length === 0) {
      uni.hideLoading();
    }
    return Promise.reject(err);
  }
}

export default {
  install
}